package com.example.common.aop;


import com.example.common.entity.LogException;
import com.example.common.mapper.LogExceptionMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 切面处理类，操作日志异常日志记录处理
 * @author YanMing
 */
@Aspect
@Component
public class LogExceptionAspect extends LogAspect {

    @Resource
    private LogExceptionMapper logExceptionMapper;


     /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* com.example.controller..*.*(..))")
    public void operationExceptionLogPoinCut() {
    }


      /**
     * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
     *
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "operationExceptionLogPoinCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        createLogException(joinPoint,e);
    }


    private void createLogException(JoinPoint joinPoint, Throwable ex){
        LogException log = (LogException) createLog(joinPoint, new LogException());

        if(log.getModule() == null || "".equals(log.getModule() )){
            log.setModule("异常");
        }
        // 异常名称
        log.setExceptionName(ex.getClass().getName());
        log.setDescribe(ex.getMessage());
        // 异常信息
        log.setExceptionMessage(stackTraceToString(ex.getClass().getName(), ex.getMessage(), ex.getStackTrace()));
        logExceptionMapper.insert(log);
    }

}
